package com.nosql.client.cli;

import com.nosql.client.api.NoSQLClient;
import com.nosql.common.protocol.DBResponse;
import com.nosql.db.core.modul.Document;

import java.io.IOException;
import java.util.*;

public class CLITool {
    private final NoSQLClient client;
    private final Scanner scanner = new Scanner(System.in);

    public CLITool(String host, int port) throws IOException {
        client = new NoSQLClient();
        client.connect(host, port);
    }

    public void start() {
        System.out.println("NoSQL CLI - Type 'help' for commands");

        while (true) {
            System.out.print("> ");
            String input = scanner.nextLine().trim();

            if (input.isEmpty()) continue;

            String[] parts = input.split("\\s+", 2);
            String command = parts[0].toLowerCase();
            String args = parts.length > 1 ? parts[1] : "";

            switch (command) {
                case "put":
                    handlePut(args);
                    break;
                case "get":
                    handleGet(args);
                    break;
                case "delete":
                    handleDelete(args);
                    break;
                case "update" :
                    handleUpdate(args);
                    break;
                case "create":
                    handleCreateCollection(args);
                    break;
                case "exit":
                    System.out.println("Exiting...");
                    return;
                case "help":
                    printHelp();
                    break;
                case "flush":
                    handleFlush(args);
                    break;

                default:
                    System.out.println("Unknown command: " + command);
            }
        }
    }

    private void handlePut(String args) {
        String[] parts = args.split("\\s+", 2);
        if (parts.length < 2) {
            System.out.println("Usage: put <collection> <field1=value1> [field2=value2 ...]");
            return;
        }

        String collection = parts[0];
        Map<String, Object> data = parseData(parts[1]);

        Document doc = new Document(collection, data);
        try {
            String serverId = client.put(collection, data);
            System.out.println("服务端生成文档ID: " + serverId);
        } catch (IOException e) {
            System.out.println("Error: " + e.getMessage());
        }
    }

    // 在CLITool类中添加以下方法
    private void handleDelete(String args) {
        String[] parts = args.split("\\s+");
        if (parts.length != 2) {
            System.out.println("Usage: delete <collection> <id>");
            return;
        }

        try {
            client.delete(parts[0], parts[1]);
            System.out.println("Document deleted successfully");
        } catch (IOException e) {
            System.out.println("Error: " + e.getMessage());
        }
    }

    // 新增修改方法
    // 修改handleUpdate方法
    private void handleUpdate(String args) {
        String[] parts = args.split("\\s+", 3);
        if (parts.length < 3) {
            System.out.println("Usage: update <collection> <id> <field1=value1> [field2=value2 ...]");
            return;
        }

        try {
            Map<String, Object> updateData = parseData(parts[2]);
            DBResponse response = client.update(parts[0], parts[1], updateData);

            // +++ 根据实际响应状态显示结果 +++
            if (response.getStatus() == DBResponse.Status.SUCCESS) {
                System.out.println("Document updated successfully");
            } else {
                System.out.println("更新失败: " + response.getError());
            }
        } catch (IOException e) {
            System.out.println("Error: " + e.getMessage());
        }
    }


    private void handleCreateCollection(String args) {
        if (args.isEmpty()) {
            System.out.println("Usage: create <collection>");
            return;
        }

        try {
            client.createCollection(args.trim());
            System.out.println("Collection '" + args + "' created successfully");
        } catch (IOException e) {
            System.out.println("Error creating collection: " + e.getMessage());
        }
    }

    private Map<String, Object> parseData(String dataStr) {
        Map<String, Object> data = new HashMap<>();
        String[] pairs = dataStr.split("\\s+");

        for (String pair : pairs) {
            String[] kv = pair.split("=", 2);
            if (kv.length == 2) {
                data.put(kv[0], parseValue(kv[1]));
            }
        }

        return data;
    }

    private Object parseValue(String value) {
        if (value.equalsIgnoreCase("true")) return true;
        if (value.equalsIgnoreCase("false")) return false;

        try {
            return Integer.parseInt(value);
        } catch (NumberFormatException e) {}

        try {
            return Double.parseDouble(value);
        } catch (NumberFormatException e) {}

        return value;
    }

    private void handleGet(String args) {
        String[] parts = args.split("\\s+");
        if (parts.length != 2) {
            System.out.println("Usage: get <collection> <id>");
            return;
        }

        try {
            Document doc = client.get(parts[0], parts[1]);
            if (doc == null) {
                System.out.println("Document not found");
            } else {
                System.out.println(doc);
            }
        } catch (IOException e) {
            System.out.println("Error: " + e.getMessage());
        }
    }
    private void handleFlush(String args) {
        if (!args.isEmpty()) {
            System.out.println("Usage: flush");
            return;
        }

        try {
            client.flush();
            System.out.println("手动刷盘成功");
        } catch (IOException e) {
            System.out.println("手动刷盘失败: " + e.getMessage());
        }
    }

    private void printHelp() {
        System.out.println("Available commands:");
        System.out.println("  put <collection> <field1=value1> [field2=value2 ...] - Create document");
        System.out.println("  get <collection> <id> - Get document by ID");
        System.out.println("  delete <collection> <id> - Delete document");
        System.out.println("  update <collection> <id> <field1=value1> [field2=value2 ...] - Update document");
        System.out.println("  create <collection> - Create new collection");
        System.out.println("  exit - Exit CLI");
    }

    public static void main(String[] args) {
        try {
            CLITool cli = new CLITool("localhost", 8080);
            cli.start();
        } catch (IOException e) {
            System.err.println("Failed to connect to server: " + e.getMessage());
        }
    }
}